//
//  SceneDelegate.swift
//  NetProject
//
//  Created by EDY on 2021/11/1.
//

import UIKit

class SceneDelegate: UIResponder, UIWindowSceneDelegate,BuglyDelegate {

    var window: UIWindow?


    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
        // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
        // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
//        let contentView = ChooseListView()
        
        if let windowScene = scene as? UIWindowScene {
            let window = UIWindow(windowScene: windowScene)
            
            self.window = window
            
            window.backgroundColor = .white
            
            SwiftBrick.navBarSmooth()
            self.setUpMainController()
            self.setUpCrashHandle()
            
        }
    }
    
    //异常捕获和处理
    func setUpCrashHandle() -> Void{
        
        //crash捕获
        crashHandle { (crashInfoArr) in
            print(crashInfoArr.count)
            var string = ""
            for info in crashInfoArr{
                //将上一次崩溃信息显示在屏幕上
                string.append(info)

            }
            UserDefaults.standard.set(string, forKey: "myCrash")
            #if DEBUG
            self.window?.makeToast(string, duration: 20, position: CSToastPositionCenter)
            #endif
            
            let filePath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first?.appending("/test")
            
                
            if !FileManager.default.fileExists(atPath: filePath!) {
                
                try? FileManager.default.createDirectory(atPath: filePath!, withIntermediateDirectories: true, attributes: nil)
            }
            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = "YYYYMMdd-HHmmss"
            let dateString =   dateFormatter.string(from: Date())
            
            
            let crashFilePath = filePath!.appending("/\(dateString).log")
            //cmDebugPrint(crashFilePath)
            
            try? string.write(toFile: crashFilePath, atomically: true, encoding: .utf8)
        }
        

        // bugly 异常捕获
        let config = BuglyConfig.init()
        config.delegate = self
        Bugly.start(withAppId: "9d4363cf01", config: config)
        
        
        if (UserDefaults.standard.string(forKey: "myCrash") != nil) {
            #if DEBUG
            self.window?.makeToast(UserDefaults.standard.string(forKey: "myCrash"), duration: 200, position: CSToastPositionCenter)
            #endif
        }
    }
    
    //设置主控制器
    func setUpMainController() -> Void{
        //初始化标题数组, 未选择图片数组, 选择图片数组, 控制器数组
        let titleArr = ["首页","热点","doki","个人中心"]
        let imageNormalArr = ["tab1_nor","tab2_nor","tab3_nor","个人tab4_nor"]
        let imageSelectedArr = ["tab1_sel","tab2_sel","tab3_sel","个人tab4_sel"]
        
        var controllersArray = [UIViewController]()
        controllersArray.removeAll()
        
        for i in 0..<titleArr.count {
            if i == 0{
                let vc = MainViewController.init()
                vc.view.backgroundColor = KbaseBlue
                let nav = BaseNavigationController.init(rootViewController: vc)
                controllersArray.append(nav)
            }else{
                let vc = ViewController.init()
                vc.view.backgroundColor = KbaseRed
                let nav = BaseNavigationController.init(rootViewController: vc)
                controllersArray.append(nav)
            }
        }
        
        //初始化配置信息
        let config : JMConfig = JMConfig.init()
        
        let tabBarVc = HomeTabbarController.init(tabBarControllers: controllersArray, norImageArr: imageNormalArr, selImageArr: imageSelectedArr, titleArr: titleArr, config: config)
        self.window?.rootViewController = tabBarVc
        self.window?.makeKeyAndVisible()
    }

    func sceneDidDisconnect(_ scene: UIScene) {
        // Called as the scene is being released by the system.
        // This occurs shortly after the scene enters the background, or when its session is discarded.
        // Release any resources associated with this scene that can be re-created the next time the scene connects.
        // The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead).
    }

    func sceneDidBecomeActive(_ scene: UIScene) {
        // Called when the scene has moved from an inactive state to an active state.
        // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
    }

    func sceneWillResignActive(_ scene: UIScene) {
        // Called when the scene will move from an active state to an inactive state.
        // This may occur due to temporary interruptions (ex. an incoming phone call).
    }

    func sceneWillEnterForeground(_ scene: UIScene) {
        // Called as the scene transitions from the background to the foreground.
        // Use this method to undo the changes made on entering the background.
    }

    func sceneDidEnterBackground(_ scene: UIScene) {
        // Called as the scene transitions from the foreground to the background.
        // Use this method to save data, release shared resources, and store enough scene-specific state information
        // to restore the scene back to its current state.
    }


}

